package com.xiaoxin.experience.service.hls.common;

import com.xiaoxin.experience.service.hls.properties.HlsProperties;

import java.util.Objects;

/**
 * @author xiaoxin
 */
public class HlsFactory
{
    private HlsFactory() {}

    private static final HlsFactory instance = new HlsFactory();

    private HlsProperties hlsProperties;

    public static HlsFactory getInstance()
    {
        return instance;
    }

    public void init(HlsProperties hlsProperties)
    {
        if (Objects.nonNull(this.hlsProperties))
        {
            return;
        }
        this.hlsProperties = hlsProperties;
        TsDownloader tsDownloader = TsDownloader.getInstance();
        tsDownloader.initTsDownloadThreadPool(hlsProperties.getThreadCount());
    }


    public void download(HlsTask hlsTask)
    {
        HlsParser parser = HlsParser.newInstance(hlsTask.getDownloadUrl())
                .retryTimes(hlsProperties.getRetryTimes()).parse();
        TsDownloader tsDownloader = TsDownloader.getInstance();

        tsDownloader.setHlsProperties(hlsProperties);
        TsDownloader.DownloadMethod method = TsDownloader.DownloadMethod.of(hlsProperties.getDownloadMethod());
        String saveFilePath = null;
        switch (method)
        {
            case DEFAULT:
                saveFilePath = tsDownloader.defaultDownload(parser,hlsTask);
                break;
            case GENERAL:
                saveFilePath = tsDownloader.generalDownload(parser,hlsTask);
                break;
            default:
                break;
        }
        hlsTask.setFileSavePath(saveFilePath);
    }
}
